/*
 * ClipPlayer.java
 * 
 * 08/11/2009
 */
package kg.sound.player.media;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;

/**
 * @author fernando
 */
public class ClipPlayer extends Player {

	private final MediaWrapper media;
	private Clip clip;

	public ClipPlayer(MediaWrapper media) throws Exception {
		this.media = media;
	}

	private Clip getClip() {
		return clip;
	}

	private void setClip(Clip clip) {
		this.clip = clip;
	}

	@Override
	protected void start() throws Exception {
		setClip(createClip());
		getClip().addLineListener(media.getLineListener());
		getClip().start();
	}

	private Clip createClip() throws Exception {
		AudioFormat format = stream.getFormat();

		/* Gather information for line creation */
		DataLine.Info info = new DataLine.Info(Clip.class, format);

		/* Check whether line is supported */
		if (!AudioSystem.isLineSupported(info)) {
			throw new RuntimeException("Line is not support for that media "
					+ "type: " + format.toString());
		}

		/* Create an empty clip using that line information */
		Clip clip = (Clip) AudioSystem.getLine(info);

		/* Open the audio stream as a clip; now it's ready to play */
		clip.open(stream);

		return clip;
	}

	@Override
	void stop() {
		getClip().stop();
	}

	@Override
	void purge() {
		getClip().removeLineListener(media.getLineListener());
		getClip().close();
		setClip(null);
	}
}